package com.tianpengtech.front.mobile.task;

import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.tianpengtech.admin.dictionary.DictionaryDao;
import com.tianpengtech.admin.task.SysConfigDao;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.model.authenticate.Authenticate;
import com.tianpengtech.common.model.dictionary.Dictionary;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.task.TaskSource;
import com.tianpengtech.common.model.task.TaskWh;
import com.tianpengtech.common.model.taskscreenshot.TaskScreenShot;
import com.tianpengtech.common.util.DateUtils;
import com.tianpengtech.common.util.XxxUtil;
import com.tianpengtech.front.mobile.common.util.R;
import com.tianpengtech.front.web.passport.AuthenticateSerivce;
import com.tianpengtech.front.web.task.TaskService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

/**
 * Created by ggd on 2017/7/28 0028.
 */
public class MobileTaskService {
	private static final String defaultAvatar = "http://www.ele-young.com/assets/front/img/x.jpg";
	// private static final String defaultAvatar =
	// "http://192.168.1.54:8090/assets/front/img/x.jpg";
	public static MobileTaskService me = new MobileTaskService();
	public static TaskService taskService = new TaskService();
	private static Task taskDao = Task.dao;
	private static Fair fairDao = Fair.dao;

	public static String PARAM_TASK_NAME = "taskName";
	public static String PARAM_TASK_STATUS = "taskStatus";

	private static String PARAM_TASK_STATUS_AFTER = "1"; // 进行中
	private static String PARAM_TASK_STATUS_END = "2"; // 已完成

	/**
	 * 待接任务列表
	 * 
	 * @return
	 */
	public R taskIndex(int pageNum, int length, long uid) {
		
		boolean isOpenFairLevel=SysConfigDao.ME.isOpenFairLevel();
		R r = R.ok();
		String s = String.format("select task.task_type,task.total_fee, task.create_user, %s,%s,%s,%s,%s,%s,%s,%s ", Task.STATUS,
				Task.ID, Task.TASK_TITLE, Task.TASK_START_TIME, Task.TASK_END_TIME, Task.TASK_DESCRIPTION,
				Task.TASK_PRICE, Task.WH_NUMBER);
		String sql = String.format(
				" from %s task where (task.%s in (?,?,?) ) and task.%s=? and task.%s=? "
//				" from %s task where (task.%s in (?,?)) and task.%s=? and task.%s=? "
//						+ "and task.%s not in(select %s from %s tw where tw.%s=?) order by task.id desc",
						+ " order by task.id desc",
				taskDao.tableName(), Task.STATUS, Task.DELETETAG, Task.EXTENSION_TYPE, Task.ID,
//				taskDao.tableName(), Task.STATUS, Task.DELETETAG, Task.EXTENSION_TYPE, Task.ID,
				TaskWh.TASK_ID, TaskWh.dao.tableName(), TaskWh.WH_ID);
		String startDate = DateUtils.formateData(new Date(), DateUtils.YYMMdd_FORMAT);

		Fair fair = Fair.dao.findById(uid);
		boolean hasApprover = (fair != null && (fair.getInt(Fair.STATUS) == Fair.STATUS_SUCCESS)) ? true : false;

		startDate = startDate + " 00:00:00";
		Page<Task> page = taskDao.paginate(pageNum, length, s, sql,
				new Object[] { Task.STATUS_SUCCESS,Task.STATUS_START,Task.STATUS_COMPLETED, Task.DELETE_STATUS_NO, Task.EXT_TYPE_RL});
//		new Object[] { Task.STATUS_SUCCESS,Task.STATUS_COMPLETED,Task.DELETE_STATUS_NO, Task.EXT_TYPE_RL, uid });
		page.getList().forEach(t -> {
			t.put("rece", t.getRece());
			t.put("statusStr", t.status());
			Authenticate auth = AuthenticateSerivce.ME.findAuthenticateByUserId(t.getInt(Task.CREATE_USER));
			String companyName = (auth == null) ? "未知" : auth.getStr(Authenticate.COMPANY_NAME);
			String logo = (auth == null) ? defaultAvatar : auth.getStr(Authenticate.LOGO);
			if (StringUtils.isEmpty(logo)) {
				logo = defaultAvatar;
			}
			t.put("company", companyName);
			t.put("companyLogo", logo);
			int type = t.getInt(Task.TASK_TYPE);
			int total = (type == Task.EXT_TYPE_RL) ? t.getInt(Task.WH_NUMBER) : t.getInt(Task.WH_NUMBER);
			t.put("total", total);
			t.put("haveAccept", queryAcceptNum(t.getLong(Task.ID), t.getInt(Task.TASK_TYPE),t.getInt(Task.WH_NUMBER)));
			t.put("dateString", t.getDateString());
			boolean result = TaskService.isExistFairTask(uid + "", t.getLong(Task.ID) + "");
			t.put("isJoin", result);
			t.put("hasApprover", hasApprover);
			//检查当前登录用户是否有资格接任务
			int priceLevel = fair.getInt(Fair.PRICE);
			boolean canApply = (priceLevel>=t.getDouble(Task.TOTAL_FEE));
			
			if(isOpenFairLevel){
				t.put("canApply", canApply);
			}else{
				t.put("canApply", true);
			}
			t.set("task_price",TaskCalculateService.ME.calculateTaskTotalFee(t));
			t.set(Task.TASK_TITLE,XxxUtil.handleContent(t.getStr(Task.TASK_TITLE), 14));
			t.set(Task.TASK_DESCRIPTION,XxxUtil.handleContent(t.getStr(Task.TASK_DESCRIPTION),103));
		
			List<TaskSource> source = taskService.findSourceByTask(t.getInt(Task.ID));
			for (TaskSource taskSource : source) {
				String ts = taskSource.getStr(TaskSource.SOURCE);
				ts = ts+"?imageMogr2/gravity/Center/100x100";
				taskSource.set(TaskSource.SOURCE, ts);
			}
			t.put("source", source);
		});
		
		r.p("pageNum", pageNum);
		r.p("task", page.getList());
		r.p("totalRow", page.getTotalRow());
		if(isSpacial(fair.getStr(Fair.MOIBILE))){
			r.p("taskTodayNum",1000);
		}else{
			r.p("taskTodayNum",taskTodayNum(uid));
		}
		return r;
	}

	public long queryAcceptNum(long taskId, int taskType,int limitNum) {
		long num = 0;
		if (taskType == Task.EXT_TYPE_ZD) {
			String sql = "select count(id) as id from fair_task_wh where task_id=?";
			num = Db.queryLong(sql, taskId);
		}
		if (taskType == Task.EXT_TYPE_RL) {
			String sql = "select count(id) as id from fair_task_wh where task_id=?";
			num = Db.queryLong(sql, taskId);
		}
		
		//num = (num>limitNum)?limitNum:num;
		return num;
	}

	public R canAcceptTaskNum(long uid) {

		String sql = String.format(
				" select count(id) as id from %s task where (task.%s=? and task.%s>=?) and task.%s=? and task.%s=? "
						+ "and task.%s not in(select %s from %s tw where tw.%s=?)",
				taskDao.tableName(), Task.STATUS, Task.TASK_START_TIME, Task.DELETETAG, Task.EXTENSION_TYPE, Task.ID,
				TaskWh.TASK_ID, TaskWh.dao.tableName(), TaskWh.WH_ID);
		R r = R.ok();
		String startDate = DateUtils.formateData(new Date(), DateUtils.YYMMdd_FORMAT);
		startDate = startDate + " 00:00:00";
		Task task = taskDao.dao().findFirst(sql,
				new Object[] { Task.STATUS_SUCCESS, startDate, Task.DELETE_STATUS_NO, Task.EXT_TYPE_RL, uid });
		r.p("totalRow", task.getLong("id"));
		return r;
	}

	/**
	 * 任务列表分页
	 * 
	 * @param
	 * @return
	 */
	public R findTask(int pageNum, int length, Map<String, Object> params) {
		List<Object> param = new ArrayList<>();
		String s = "select wh.status as wh_status,task.total_fee, task.wh_number,task.task_type ,task.create_user,task.task_title,task.task_description,task.task_price,task.status as status,task.id as id,task.task_start_time,task.task_end_time ";
		StringBuffer sql = new StringBuffer(" from " + taskDao.tableName() + " task left join " + TaskWh.dao.tableName()
				+ " wh on task." + Task.ID + "=wh." + TaskWh.TASK_ID + " left join " + Fair.dao.tableName()
				+ " fair on fair." + Fair.ID + "=wh." + TaskWh.WH_ID);
		sql.append(" where task." + Task.DELETETAG + "=? and wh." + TaskWh.WH_ID + "=? and task." + Task.STATUS + " not in ("
				+ Task.STATUS_WAIT+","+Task.STATUS_APPROVING+")");
		param.add(Task.DELETE_STATUS_NO);
		long userId = (Long) params.get("user");

		// Fair fair= Fair.dao.findById(userId);
		//
		// boolean hasApprover = (fair!=null &&
		// (fair.getInt(Fair.STATUS)==Fair.STATUS_SUCCESS))?true:false;
		param.add(userId);
		if (params != null) {
			Object taskName = params.get(PARAM_TASK_NAME);
			Object taskStatus = params.get(PARAM_TASK_STATUS);
			if (taskName != null && StrKit.notBlank(taskName.toString())) {
				sql.append(" and (");
				sql.append("task." + Task.TASK_TITLE + " like ? or ");
				param.add("%" + taskName.toString() + "%");
				sql.append("fair." + Fair.NICK_NAME + " like ?)");
				param.add("%" + taskName.toString() + "%");
			}
			if (taskStatus != null && StrKit.notBlank(taskStatus.toString())) {
				sql.append(" and (");
				if (taskStatus.toString().equals(PARAM_TASK_STATUS_AFTER)) {
//					sql.append("task." + Task.STATUS + "=? and task." + Task.TASK_START_TIME + "<?)");
					sql.append("wh." + Task.STATUS + " =? )");
					param.add(Task.STATUS_START);
//					String dateTime = DateUtils.formateData(new Date(), DateUtils.YYMMdd_FORMAT) + " 00:00:00";
//					param.add(dateTime);
				} else if (taskStatus.toString().equals(PARAM_TASK_STATUS_END)) {
					sql.append("wh." + Task.STATUS + "=?)");
					param.add(Task.STATUS_COMPLETED);
				}
			}
			sql.append(" group by task." + Task.ID + " order by task." + Task.ID + " DESC");
		}
		Page<Task> page = taskDao.paginate(pageNum, length, s, sql.toString(), param.toArray());
		List<Task> tasks = page.getList();
		for (Task t : tasks) {
			t.put("statusStr", t.status());
			t.put("dateString", t.getDateString());
			t.put("statusStr", t.status());
			Authenticate auth = AuthenticateSerivce.ME.findAuthenticateByUserId(t.getInt(Task.CREATE_USER));
			String companyName = (auth == null) ? "未知" : auth.getStr(Authenticate.COMPANY_NAME);
			String logo = (auth == null || StringUtils.isBlank(auth.getStr(Authenticate.LOGO))) ? defaultAvatar
					: auth.getStr(Authenticate.LOGO);
			t.put("company", companyName);
			t.put("companyLogo", logo);

			t.set(Task.TASK_TITLE,XxxUtil.handleContent(t.getStr(Task.TASK_TITLE), 14));
			
			int type = t.getInt(Task.TASK_TYPE);
			
			int total = (type == Task.EXT_TYPE_RL) ? 200 : t.getInt(Task.WH_NUMBER);
			t.put("total", total);
			t.set("task_price",TaskCalculateService.ME.calculateTaskTotalFee(t));
			t.put("haveAccept", queryAcceptNum(t.getLong(Task.ID), type,t.getInt(Task.WH_NUMBER)));
			boolean result = TaskService.isExistFairTask(params.get("user") + "", t.getLong(Task.ID) + "");
			t.put("isJoin", result);
			// t.put("hasApprover", hasApprover);
			t.set(Task.TASK_TITLE,XxxUtil.handleContent(t.getStr(Task.TASK_TITLE), 14));
			t.set(Task.TASK_DESCRIPTION,XxxUtil.handleContent(t.getStr(Task.TASK_DESCRIPTION),103));
			
			List<TaskSource> source = taskService.findSourceByTask(t.getInt(Task.ID));
			for (TaskSource taskSource : source) {
				String ts = taskSource.getStr(TaskSource.SOURCE);
				ts = ts+"?imageMogr2/gravity/Center/100x100";
				taskSource.set(TaskSource.SOURCE, ts);
			}
			t.put("source", source);
		}
		R r = R.ok();
		r.p("count", page.getTotalRow());
		r.p("pageNum", page.getPageNumber());
		r.p("totalPage", page.getTotalPage());
		r.p("list", page.getList());
		r.p("isLastPage", page.isLastPage());
		return r;
	}

	public R getTask(long id, long uid) {
		StringBuffer sql = new StringBuffer(
				"select task.total_fee,task.extension_type,task.wh_number,task.task_type ,wh.reason ,wh.title as rec_title, wh.status as wh_status, wh.code, task.task_url, task.create_user, task.task_title,task.task_description,task.task_price,task.status as status,task.id as id,task.task_start_time,task.task_end_time,wh.click_num,wh.cvs_num,wh.id as whid,task.task_url from "
						+ taskDao.tableName() + " task left join " + TaskWh.dao.tableName() + " wh on task." + Task.ID
						+ "=wh." + TaskWh.TASK_ID + " where wh." + TaskWh.TASK_ID + "=? and wh." + TaskWh.WH_ID + "=?");
		Task task = taskDao.findFirst(sql.toString(), id, uid);
		String url ="http://www.ele-young.com/platform/mission?id=" + id;
//		String url ="http://192.168.1.101:8091/platform/mission?id=" + id;
		
		if (task == null) {
			sql = new StringBuffer(
					"select task.total_fee,task.extension_type,task.wh_number,task.task_type, wh.reason , wh.code,task.task_url, task.create_user,task.task_title,task.task_description,task.task_price,task.status as status,task.id as id,task.task_start_time,task.task_end_time,wh.click_num,wh.cvs_num,wh.id as whid,task.task_url from "
							+ taskDao.tableName() + " task left join " + TaskWh.dao.tableName() + " wh on task."
							+ Task.ID + "=wh." + TaskWh.TASK_ID + " where task." + Task.ID + "=?");
			task = taskDao.findFirst(sql.toString(), id);
			task.put("sumClick",task.getClick());
			task.put("sumCvs",task.getCvs());
			task.put("click_num",0);
			task.put("cvs_num",0);
			task.put("actual_price",0);
			
		} else {
			task.put("sumClick", task.getClick());
			task.put("sumCvs", task.getCvs());
//			task.put("sumClick",task.getLong(TaskWh.CLICK_NUM));
//			task.put("sumCvs", task.getLong(TaskWh.CVS_NUM));
			task.put("click_num",task.getLong(TaskWh.CLICK_NUM));
			task.put("cvs_num",task.getLong(TaskWh.CVS_NUM));
			long click_num =task.getLong(TaskWh.CLICK_NUM);
			task.put("actual_price",TaskCalculateService.ME.IShouldPayHowMuchMoney(click_num, task));
			if(task.getStr("code")!=null){
				url =url+ "&ucode=" + task.getStr("code");
			}
		}
		boolean isOpenFairLevel=SysConfigDao.ME.isOpenFairLevel();
		Fair fair = Fair.dao.findById(uid);
		int priceLevel = fair.getInt(Fair.PRICE);
		boolean canApply = (priceLevel>=task.getDouble(Task.TOTAL_FEE));
		if(isOpenFairLevel){
			task.put("canApply", canApply);
		}else{
			task.put("canApply", true);
		}
		
		task.set("task_price",TaskCalculateService.ME.calculateTaskTotalFee(task));
		task.put("dateString", task.getDateString());
		Authenticate auth = AuthenticateSerivce.ME.findAuthenticateByUserId(task.getInt(Task.CREATE_USER));
		String companyName = (auth == null) ? "未知" : auth.getStr(Authenticate.COMPANY_NAME);
		long companyId = (auth == null) ? 0 : auth.getLong(Authenticate.ID);
		String logo = (auth == null || StringUtils.isBlank(auth.getStr(Authenticate.LOGO))) ? defaultAvatar
				: auth.getStr(Authenticate.LOGO);
		task.put("company", companyName);
		task.put("companyId", companyId);
		task.put("companyLogo", logo);
//		
		List<TaskSource> source = taskService.findSourceByTask(task.getInt(Task.ID));
		
		for (TaskSource taskSource : source) {
			String s = taskSource.getStr(TaskSource.SOURCE);
			s = s+"?imageMogr2/gravity/Center/100x100";
			taskSource.set(TaskSource.SOURCE, s);
		}
		
		task.put("task_url", url);
		task.put("task_count_url", "http://ele-young.com/h5/appTaskStatistical/analysis.html?taskId="+task.getInt(Task.ID)+"&whId="+fair.getInt(Fair.ID));
		R r = R.ok();
		r.p("task", task);
		task.put("acceptNum", 0);
		
		int wh_num = (task.getInt(Task.EXTENSION_TYPE)==Task.EXT_TYPE_RL)?200:task.getInt(Task.WH_NUMBER);
		// if (task.getInt("status")!=Task.STATUS_SUCCESS) {
		String fairs = String.format(
				"select wt.code, wh.descript as descript, wh.photo,wh.nick_name,wh.id as id,task.task_price,wt.cvs_num,wt.click_num,wt.wh_id from %s wt "
				+ "left join %s wh on wt.%s=wh.%s left join %s task on wt.%s=task.%s where wt.%s=? "
				+ "order by wt.%s desc limit "+ wh_num,
				TaskWh.dao.tableName(), Fair.dao.tableName(), TaskWh.WH_ID, Fair.ID, Task.dao.tableName(),
				TaskWh.TASK_ID, Task.ID, TaskWh.TASK_ID, TaskWh.CLICK_NUM);
		List<Fair> fairses = fairDao.find(fairs, id);
		for (int i = 0; i < fairses.size(); i++) {
			//假如包含自己，则剔除自己再列表中的位置
			Fair f = fairses.get(i);
//			if(f.getLong(TaskWh.WH_ID)==uid){
//				fairses.remove(f);
//				continue;
//			}
			f.put("no", i + 1);
			String photo = ((f.getStr(Fair.PHOTO).equals("/upload/avatar/x.jpg")) ? defaultAvatar
					: f.getStr(Fair.PHOTO));
			f.set(Fair.PHOTO, photo);
			long click_num =f.getLong(TaskWh.CLICK_NUM);
			f.put("task_price",TaskCalculateService.ME.IShouldPayHowMuchMoney(click_num, task));
			
			String fairUrl ="http://www.ele-young.com/platform/mission?id=" + id;
//			String fairUrl ="http://192.168.1.101:8091/platform/mission?id=" + id;
			if(f.getStr("code")!=null){
				fairUrl =fairUrl+ "&ucode=" + f.getStr("code");
			}
			f.put("fairUrl",fairUrl);
		}
		r.p("fairs", fairses);
		r.p("source", source);
		int num = (fairses.isEmpty()) ? 0 : fairses.size();
		task.put("acceptNum", num);
		// }
		boolean result = TaskService.isExistFairTask(uid + "", id + "");
		task.put("isJoin", result);
		boolean hasApprover = (fair != null && (fair.getInt(Fair.STATUS) == Fair.STATUS_SUCCESS)) ? true : false;
		task.put("hasApprover", hasApprover);
		task.put("wh_status", Task.STATUS_COMPLETED);
		String photo = ((fair.getStr(Fair.PHOTO).equals("/upload/avatar/x.jpg")) ? defaultAvatar
				: fair.getStr(Fair.PHOTO));
		task.put("myAvatar",photo);
		task.put("wh_id",uid);
		return r;
	}

	/**
	 * 接受任务
	 * 
	 * @param taskId
	 * @param uid
	 * @return
	 */
	public R acceptTask(String taskId, long uid) {
		Ret ret = new Ret();
		R r;
		
		//检查当前网红是否能够有资格接受当前任务信息
		Task task = Task.dao.findById(taskId);
		Fair fair = Fair.dao.findById(uid);
		//检查任务类型，假如任务已经超过指定任务，则通知不能在报名了
		int fairPrice = fair.getInt(Fair.PRICE);
		
		boolean isOpenFairLevel = SysConfigDao.ME.isOpenFairLevel();//检查是否需要放开网红接单任务控制
		
		if(isOpenFairLevel){
			if(fairPrice<task.getInt(Task.TOTAL_FEE)){
				r = R.fail("根据系统限定，你暂时不能接受当前任务");
				return r;
			}
		}
		
		//将报名信息加入报名的队列信息，获取生成的唯一的自助ID数据
		Record record = new Record();
		int pre_apply=1;//预报名
		record.set("wh_id", uid);
		record.set("task_id", taskId);
		record.set("status", pre_apply);
		Db.save("fair_task_queue", record);
		int queueId = record.getInt("id");
		
		if(queueId<=0){
			r = R.fail("报名排队失败");
			return r;
		}
		
		//检查当前网红报名任务个数是否超过系统设定值，假如超过，则提示信息
		Dictionary dictionary = DictionaryDao.ME.readDirecotryByCode(Dictionary.SYS_APPLY_NUM);
		int applyNum = Integer.parseInt(dictionary.getStr(Dictionary.NAME));
		List<TaskWh> wh_tasks = queryFairWhTasksToday(uid);
		
		//添加特殊帐号，让其无限接受任务
		
		if(wh_tasks.size()>=applyNum && (!isSpacial(fair.getStr(Fair.MOIBILE)))){
			r = R.fail("你每天只能接受"+applyNum+"个任务");
			return r;
		}
		
		boolean result = TaskService.isExistFairTask(uid + "", taskId);
		if (result) {
			r = R.fail("你已经接受了当前任务，请勿重复操作！！");
			return r;
		}
		
		int wh_num = (task.getInt(Task.EXTENSION_TYPE)==Task.EXT_TYPE_RL)?200:task.getInt(Task.WH_NUMBER);
		List<TaskWh> taskWh= TaskService.queryFairApplyNumTask(taskId);
		if(taskWh.size()>=wh_num){
			r = R.fail("报名人数已经够了,感谢你的关注");
			return r;
		}
		
		ret = taskService.saveTaskWait(new String[] { uid + "" }, taskId);
		if (ret.isOk()) {
			Db.update("update fair_task_queue set status=2 where id=?",queueId);//将预报名信息变成正式报名状态，此时报名task_wh表中才有一条正式的报名信息
			r = R.ok();
		} else {
			r = R.fail(ret.getStr("msg"));
		}
		return r;
	}
	
	private boolean isSpacial(String mobile){
		String special="18268114484,18721608514,15720605907,13819492790,13262535273";
		return special.contains(mobile);
	}

	public R isExistFairTask(String taskId, long uid) {
		R r;
		boolean result = TaskService.isExistFairTask(uid + "", taskId);
		if (result) {
			r = R.ok("参加过任务");
			r.p("isJoin", true);
		} else {
			r = R.ok("没有参加过任务");
			r.p("isJoin", false);
		}
		return r;
	}
	
	
	public void missionCommit(int type,int taskId,long fairId,String screenShot) throws ValidateException{
		
		
		//检查当前网红是否参加过当前任务
		
		String sql="select * from "+TaskWh.dao.tableName()+" where wh_id=? and task_id=?";
		TaskWh taskWh= TaskWh.dao.findFirst(sql,fairId,taskId);
		
		if(taskWh==null){
			throw new ValidateException("你没有参与当前任务，无需提交任务截图");
		}
		
		sql="select * from "+TaskScreenShot.dao.tableName()+" where task_id=? and fair_id=? and type=?";
		TaskScreenShot temp = TaskScreenShot.dao.findFirst(sql,taskId,fairId,type);
		
		if(temp!=null){
			throw new ValidateException("任务截图已经提交，请勿重复操作");
		}
		TaskScreenShot shot = new TaskScreenShot();
		shot.set(TaskScreenShot.TASK_ID, taskId);
		shot.set(TaskScreenShot.FAIR_ID, fairId);
		shot.set(TaskScreenShot.IMG, screenShot);
		shot.set(TaskScreenShot.TYPE, type);
		shot.save();
	}
	
	
	public R missionCommitList(int taskId,long fairId){
	
		String sql="select * from "+TaskScreenShot.dao.tableName()+" where task_id=? and fair_id=? order by id desc";
		List<TaskScreenShot> temp = TaskScreenShot.dao.find(sql,taskId,fairId);
		R r = R.ok();
		r.p("list", temp);
		return r;
	}
		
	public void updateRecomandReason(int taskId,long fairId,String reason,String title) throws ValidateException{
		
		if(StringUtils.isEmpty(title)){
			throw new ValidateException("推荐标题不能为空!!");
		}
		
		if(title.length()>10){
			throw new ValidateException("推荐标题不能超过10个字符!!");
		}
		
		if(StringUtils.isEmpty(reason)){
			throw new ValidateException("推荐理由不能为空!!");
		}
		
		if(reason.length()>30){
			throw new ValidateException("推荐理由不能超过30个字符!!");
		}
		
		String sql="update fair_task_wh set reason=?,title=? where task_id=? and wh_id=?";
		Db.update(sql,reason,title,taskId,fairId);
	}
	
	
	public int taskTodayNum(long wh_id){
		List<TaskWh> tasks =queryFairWhTasksToday(wh_id);
		int acceptNum = tasks.size();
		Dictionary dictionary = DictionaryDao.ME.readDirecotryByCode(Dictionary.SYS_APPLY_NUM);
		int sysApplyNum = Integer.parseInt(dictionary.getStr(Dictionary.NAME));
		int result = (sysApplyNum-acceptNum<=0)?0:sysApplyNum-acceptNum;
		return result;
	}
	
	
	public boolean delMissionCommit(int id){
		return TaskScreenShot.dao.deleteById(id);
	}
		
	
	private List<TaskWh> queryFairWhTasksToday(long wh_id){
		Date today = new Date();
		String start=DateUtils.formateData(today, DateUtils.YYMMdd_FORMAT);
		start = start+" 00:00:00";
		String end=DateUtils.formateData(today, DateUtils.YYMMdd_FORMAT);
		end = end+" 23:59:59";
		String sql="select * from "+TaskWh.dao.tableName()+" where wh_id=? and create_time between ? and ? and status=? ";
		return  TaskWh.dao.find(sql,wh_id,start,end,Task.STATUS_START);
	}
}
